<template>
	<div>
		<a-modal
			:open="props.open"
			:width="
				props.modelInfo && props.modelInfo.width ?
					props.modelInfo.width
				:	'900px'
			"
			:title="
				props.modelInfo && props.modelInfo.title ?
					props.modelInfo.title
				:	'Basic Modal'
			"
			@ok="handleOk"
			okText="保存"
			:confirmLoading="modelConfig.confirmLoading"
			:destroyOnClose="modelConfig.destroyOnClose"
			@cancel="handleCancel"
		>
			<template #footer>
				<a-button key="back" @click="handleCancel">取消</a-button>
				<a-button
					key="submit"
					type="primary"
					:loading="loading"
					@click="handleOk"
					>保存</a-button
				>
			</template>
			<a-form
				ref="formRef"
				name="UserMembershipInfoForm"
				class="ant-advanced-search-form"
				:model="formState"
				@finish="onFinish"
				@finishFailed="onFinishFailed"
				:rules="rulesRef"
				:label-col="labelCol"
				:wrapper-col="wrapperCol"
			>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['userId'].name"
							:label="labelMap['userId'].label"
						>
							<a-select
								v-model:value="formState.userId"
								:placeholder="'请填写' + labelMap['userId'].label"
								:options="userList"
								:filter-option="filterOption"
								:field-names="{ value: 'id', label: 'code' }"
								show-search
								allow-clear
							>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['membershipId'].name"
							:label="labelMap['membershipId'].label"
						>
							<a-select
								:placeholder="'请选择' + labelMap['membershipId'].label"
								v-model:value="formState.membershipId"
								style="width: 100%"
								:options="membershipList"
								:field-names="{ value: 'id', label: 'membershipName' }"
								allow-clear
								@change="handleMembershipChange"
							>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['amount'].name"
							:label="labelMap['amount'].label"
						>
							{{ currentPrice ? currentPrice + '元' : '' }}
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script lang="ts" setup>
import { UserMembershipInfoDetail } from './userMembershipInfoDetailTs';
import {
	getUserMembershipInfoDetail,
	addOrEditUserMembershipInfo,
	addUserMembership,
} from '@/api/membershipInfo/userMembershipInfo/userMembershipInfoTs';
import { getMembershipConfigurationList } from '@/api/membershipInfo/membershipConfiguration/membershipConfigurationTs';
import { getUserInfoList } from '@/api/userInfo/userInfo/userInfoTs';
import { message, FormInstance } from 'ant-design-vue';
import { ModelInfo } from '../userMembershipInfoListTs';
import { filterOption } from '@/utils/common';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const membershipList = ref<any[]>();

const currentPrice = ref<any>(null);

const labelMap = ref<any>({
	userId: { name: 'userId', label: '系统用户' },
	membershipId: { name: 'membershipId', label: '会员' },
	startTime: { name: 'startTime', label: '会员开始时间' },
	endTime: { name: 'endTime', label: '会员结束时间' },
	amount: { name: 'amount', label: '会员金额' },
});

const rulesRef = reactive({
	userId: [
		{
			required: true,
			message: '系统用户不能为空！',
		},
	],
	membershipId: [
		{
			required: true,
			message: '会员不能为空！',
		},
	],
	startTime: [
		{
			required: true,
			message: '会员开始时间不能为空！',
		},
	],
	endTime: [
		{
			required: true,
			message: '会员结束时间不能为空！',
		},
	],
});

const modelConfig = {
	confirmLoading: true,
	destroyOnClose: true,
};

interface Props {
	open?: boolean;
	modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<UserMembershipInfoDetail>({});

const userList = ref<any[]>([]);

const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
	loading.value = true;
	if (formRef.value) {
		formRef.value
			.validateFields()
			.then(() => saveUserMembershipInfoManager())
			.catch(() => {
				loading.value = false;
			});
	}
};

const handleCancel = (): void => {
	emit('handleCancel', false);
};

//保存用户会员表信息
const saveUserMembershipInfoManager = async (): Promise<void> => {
	let params = {
		userId: formState.value.userId,
		membershipId: formState.value.membershipId,
		source: 'end',
	};
	const { code, message: messageInfo } = await addUserMembership(
		params,
	).finally(() => (loading.value = false));
	if (code == '200') {
		message.success('创建订单成功，请到订单中进行审核！');
		emit('handleOk', false);
	} else {
		message.error(messageInfo || '保存失败！');
	}
	// if (formState.value.id) {
	// 	method = 'put';
	// } else {
	// 	method = 'post';
	// }
	// addOrEditUserMembershipInfo(method, formState.value)
	// 	.then((res) => {
	// 		if (res.code == '200') {
	// 			message.success((res && res.message) || '保存成功！');
	// 			emit('handleOk', false);
	// 		} else {
	// 			message.error((res && res.message) || '保存失败！');
	// 		}
	// 		formState.value = {};
	// 	})
	// 	.catch((error: any) => {
	// 		message.error(error?.message || '保存失败！');
	// 	})
	// 	.finally(() => {
	// 		loading.value = false;
	// 	});
};

const onFinish = (values: any): void => {
	console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
	console.log('Failed:', errorInfo);
};

// 查询会员配置列表
const getMembershipConfigurationListInfo = async () => {
	let res = await getMembershipConfigurationList({});
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		membershipList.value = data;
	} else {
		message.warn(messageInfo?.description || '失败，请联系管理员！');
	}
};

// 查询用户信息
const getUserInfoListInfo = async () => {
	console.log(`getUserInfoList`);
	let params = {};
	let res = await getUserInfoList(params);
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		userList.value = data;
	} else {
		userList.value = [];
		message.warn(messageInfo || '失败，请联系管理员！');
	}
};

const handleMembershipChange = (value: any, option: any) => {
	currentPrice.value = option.currentPrice;
};

const init = (): void => {
	getMembershipConfigurationListInfo();
	getUserInfoListInfo();
	if (props.modelInfo) {
		if (props.modelInfo.id) {
			getUserMembershipInfoDetail(props.modelInfo.id)
				.then((res) => {
					if (res.code == '200') {
						formState.value = res.data;
						modelConfig.confirmLoading = false;
					} else {
						message.error((res && res.message) || '查询失败！');
					}
				})
				.catch((error: any) => {
					let data = error?.response?.data;
					if (data) {
						message.error(data?.message || '查询失败！');
					}
				});
		} else {
			modelConfig.confirmLoading = false;
			formState.value = {};
		}
	}
};

watch(
	() => props.open,
	(newVal) => {
		if (newVal) {
			init();
		}
	},
	{
		immediate: true,
		deep: true,
	},
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang="scss" scoped></style>
